package com.smartystars.quizzer;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Map;

import android.util.Log;

import com.smartystars.quizzerServer.DownloadableQuestions;
import com.smartystars.quizzerServer.ExternalStorage;


/**
 * 
 * @author Dominik v.d.Heydt
 * 
 */
public class NetworkThread extends Thread{
	private String request;
	private int score;
	private String SERVERIP = "domhey.no-ip.biz";
	private int SERVERPORT = 4090;
	private String language;
	private File sdCard;
	private File questions;
	
public NetworkThread(String request ,String language, int score){
	this.request=request;
	this.score = score;
	this.language = language;
}
	
	
public void run(){
	
	if(request.equals("DOWNLOAD")){
		try {
			Socket serverSocket;
			InetAddress serverAddr = InetAddress.getByName(SERVERIP);
			serverSocket = new Socket(serverAddr,SERVERPORT);
			PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(
					serverSocket.getOutputStream()));
			printWriter.print(language);
			printWriter.flush();
			
			ObjectInputStream in = null;
			in = new ObjectInputStream(new BufferedInputStream(serverSocket.getInputStream()));
			DownloadableQuestions dQuestions = (DownloadableQuestions) in.readObject();
			
			//dQuestions.writeQuestionsToDisk();
			writeQuestionsToDisk(dQuestions);
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}
	
public void writeQuestionsToDisk(DownloadableQuestions dQuestions){
	Map<String, File> externalLocations = ExternalStorage
			.getAllStorageLocations();
	sdCard = externalLocations.get(ExternalStorage.SD_CARD);
	
	questions = new File(sdCard + "/Quizzer/questions.ser");
	
	if(!questions.exists()){
		new File(sdCard + "/Quizzer/").mkdir();
		try {
			questions.createNewFile();
		} catch (IOException e) {
			Log.i("File", "questions.ser could not be created");
		}
		
	}
	
	ObjectOutputStream oos = null;
	FileOutputStream fos = null;
	try {
	  fos = new FileOutputStream(questions);
	  oos = new ObjectOutputStream(fos);
	  oos.writeObject(dQuestions);
	}
	catch (IOException e) {
	  e.printStackTrace();
	}
	finally {
	  if (oos != null) try { oos.close(); } catch (IOException e) {}
	  if (fos != null) try { fos.close(); } catch (IOException e) {}
	}

	
	
}	
	
	
}
